package com.niezhiliang.netty.websocket.spring.boot.demo.service.other;

import com.niezhiliang.netty.websocket.spring.boot.demo.service.other.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("NettyUdpServer")
public class NettyUdpServer {

    @Autowired
    private UdpServerHandler udpServerHandler;

    public void startNettyUdpServer() {
        EventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class) // 使用UDP通道
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(udpServerHandler); // 自定义UDP服务器处理器
                        }
                    });

            ChannelFuture future = bootstrap.bind(9876).sync(); // 绑定UDP端口

            System.out.println("UDP Server started and listening on port 9876...");

            future.channel().closeFuture().sync(); // 等待服务器Socket关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}

